<template>
  <!-- 搜索区域 -->
  <ContentWrap>
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="表单名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入表单名"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable class="!w-240px">
          <el-option
            v-for="dict in common_enable_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" />
          重置
        </el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['bpm:form:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" />
          新增
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表区域 -->
  <ContentWrap>
    <el-table v-loading="listLoading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="编号" prop="id" width="200" />
      <el-table-column label="表单名" prop="name" />
      <!--      <el-table-column label="表单配置" prop="conf" />-->
      <!--      <el-table-column label="表单组件规则" prop="fields" />-->
      <el-table-column label="备注" prop="remark" />
      <el-table-column label="状态" prop="status">
        <template #default="scope">
          <dict-tag :options="common_enable_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createTime" width="200" />
      <el-table-column label="操作" width="260" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['bpm:form:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="primary"
            @click="openForm('copy', scope.row.id)"
            v-hasPermi="['bpm:form:create']"
          >
            复制
          </el-button>
          <el-button
            link
            type="primary"
            @click="openDetail(scope.row.id)"
            v-hasPermi="['bpm:form:query']"
          >
            演示
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['bpm:form:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页区域 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：详情 -->
  <Dialog v-model="detailVisible" title="表单演示" width="800">
    <form-create
      :rule="detailData.rule"
      :option="detailData.option"
      @submit="handleDetailFormSubmit"
      @change="handleDetailFormChange"
    />
  </Dialog>
</template>

<script setup lang="ts">
import { FormApi, FormVO } from '@/api/bpm/form'
import { setFormConfAndFields } from '@/utils/formCreate'

/** BPM表单定义 列表 */
defineOptions({ name: 'BpmForm' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const route = useRoute()
const { push } = useRouter() // 路由
const { common_enable_status } = useIntDict(DICT_TYPE.common_enable_status)

const listLoading = ref(true) // 列表的加载中状态
const list = ref<FormVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  name: undefined,
  status: undefined,
  createTime: [],
  pageNo: 1,
  pageSize: 10
})
const queryFormRef = ref() // 搜索的表单

/** 查询列表 */
const getList = async () => {
  listLoading.value = true
  try {
    const data = await FormApi.getFormPage(queryParams)
    list.value = data.content
    total.value = data.totalElement
  } finally {
    listLoading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const openForm = (type: string, id?: number) => {
  // push({ path: '/bpm/form/manage/edit', query: { id: id } })
  // 使用路由名称的方式，以便后续可以方便调整路由的path
  push({ name: 'BpmFormEditor', query: { type, id } })
}

const detailVisible = ref(false)
const detailData = ref({
  rule: [],
  option: {}
})
const openDetail = async (id: number) => {
  const data = await FormApi.getForm(id)
  setFormConfAndFields(detailData, data.conf, data.fields, false, true)  // 这里不禁用按钮
  detailVisible.value = true
}

const handleDetailFormSubmit = (formData) => {
  console.log(JSON.stringify(formData))
}

const handleDetailFormChange = (field, value, rule, api, setFlag) => {
  console.log('form change:', field, value, rule, api, setFlag, api.getRule(field))
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 弹出确认框
    await message.delConfirm()
    // 发起删除请求
    await FormApi.deleteForm(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 表单保存返回后，重新加载列表 */
const firstLoad = ref(true)
onActivated(() => { // keepalive组件才会启用，首次装载会在onMounted之后执行，后续从keepalive中被激活也会执行
  if (firstLoad.value) {  // 确保不与onMounted重复执行逻辑
    firstLoad.value = false
    return
  }
  if (history.state?.reload) {
    getList()
  }
})

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>

<style scoped lang="scss"></style>
